<!--协定药品-->
<template>
  <Popup
    v-model:visible="popupVisible"
    :drag-enabled="false"
    :close-on-outside-click="false"
    :show-close-button="true"
    :show-title="true"
    :width="650"
    :height="595"
    @isReady="initPopup"
    @hidden="hidden"
    title="自制药品组成"
  >
    <DxScrollView width="100%" height="100%" style="padding-bottom: 30px">
      <DxForm label-location="left" :col-count="1">
        <DxGroupItem>
          <div class="center-title">
            <el-alert
              title="选中具体规格药品，按剂量单位指定具体的组成药品；未指定其组成（或清除其组成），本药品将不会做为协定药品"
              type="warning"
              :closable="false"
            />
          </div>
        </DxGroupItem>
        <DxGroupItem>
          <DxSimpleItem data-field="">
            <div class="custom-form-item">
              <p>药品品种：</p>
              <div>
                <DxTextBox
                  stylingMode="outlined"
                  :disabled="true"
                  :value="drugDetail.name"
                />
                <div class="notice">
                  <el-tag type="error" :closable="false" class="word1">
                    规格：{{ drugDetail.dosageName }}
                  </el-tag>
                  <el-tag type="success" :closable="false" class="word1">
                    计量单位：{{ drugDetail.dosageUnitName }}
                  </el-tag>
                </div>
              </div>
            </div>
          </DxSimpleItem>
        </DxGroupItem>

        <DxGroupItem>
          <div class="center-title">
            <div style="font-size: 16px; width: 200px">组成药品:</div>
            <DxButton type="text" icon="plus" @click="add"></DxButton>
          </div>
        </DxGroupItem>
        <DxSimpleItem>
          <template #default>
            <div v-for="(item, index) in agreeDrugList" :key="index">
              <div class="item-template">
                <DxCheckBox v-model:value="item.selected"></DxCheckBox>
                <p>名称</p>
                <DxSelectBox
                  v-bind="durgSetting"
                  :dataSource="drugDatalist"
                  v-model:value="item.drugId"
                  @valueChanged="drugChange(index)"
                ></DxSelectBox>
                <p>规格</p>
                <DxSelectBox
                  v-bind="skuSetting"
                  :items="item.specificationList"
                  v-model:value="item.specificationId"
                ></DxSelectBox>
                <p style="width: 70px">采用量</p>
                <DxTextBox v-model:value="item.adoption" />
              </div>
              <div class="notice">
                <el-tag type="error" :closable="false" class="word1">
                  规格：{{
                    getSkuName(item.specificationId, item.specificationList)
                  }}
                </el-tag>
                <el-tag type="success" :closable="false" class="word1">
                  计量单位：{{ drugDetail.dosageUnitName }}
                </el-tag>
              </div>
            </div>
          </template>
        </DxSimpleItem>
      </DxForm>
    </DxScrollView>
    <div class="lb-form-button-left">
      <DxButton
        text="删除"
        styling-mode="text"
        type="danger"
        @click="deleteItem()"
      />
    </div>
    <div class="lb-form-button-right">
      <DxButton text="取消" styling-mode="text" @click="hidden()" />
      <DxButton
        text="确定"
        styling-mode="text"
        type="default"
        @click="submit()"
      />
      <!-- @click="save" -->
    </div>
  </Popup>
</template>

<script lang="ts">
import { DxPopup } from "devextreme-vue/popup";
import {
  DxForm,
  DxSimpleItem,
  DxGroupItem,
  DxRequiredRule,
  DxLabel,
} from "devextreme-vue/form";
import DxTagBox from "devextreme-vue/tag-box";
import DxCheckBox from "devextreme-vue/check-box";
import { ElButton, ElIcon, ElTag, ElAlert } from "element-plus";
import {
  Vue,
  Options,
  Prop,
  Watch,
  Inject,
  Emit,
} from "vue-property-decorator";
import { DxColumn, DxDataGrid, DxEditing } from "devextreme-vue/data-grid";
import DataSource from "devextreme/data/data_source";
import DxButton from "devextreme-vue/button";
import { dxSelectBoxOptions } from "devextreme/ui/select_box";
import { DxSelectBox } from "devextreme-vue/select-box";
import { DxTextBox } from "devextreme-vue/text-box";
import Popup from "@/framework/components/popup/popup.vue";
import DrugData from "@/data-source/drug";
import DrugSkuData from "@/data-source/drug-sku";
import DrugAgreeData from "@/data-source/drug-agree";
import {
  BatchInsertOrUpdateSelfMadeDrugInput,
  InsertOrUpdateSelfMadeDrugInput,
  OutPutDrugInfo,
  OutputSpecificationSimpleModel,
} from "@/api/api_agreementdrugclient";
import { ApiTool } from "@/api/api-tool";
import { DrugClient } from "@/api/api_drugclient";
import { SpecificationClient } from "@/api/api_specificationclient";
import { DxScrollView } from "devextreme-vue/scroll-view";
import DrugMadeData from "@/data-source/drug-made";
import { SelfMadeDrugClient } from "@/api/api_selfmadedrugclient";

interface AgreeDrug {
  selected: boolean;
  drugId: string;
  specificationId: string;
  adoption: number;
  specificationList: any[];
}
@Options({
  components: {
    DxPopup,
    DxForm,
    DxSimpleItem,
    DxGroupItem,
    DxRequiredRule,
    DxLabel,
    DxTagBox,
    DxCheckBox,
    ElButton,
    Popup,
    DxColumn,
    DxDataGrid,
    DxEditing,
    DxButton,
    ElIcon,
    ElAlert,
    ElTag,
    DxSelectBox,
    DxTextBox,
    DxScrollView,
  },
})
export default class CreateDrugAgree extends Vue {
  // 药品类型
  @Prop()
  drugType: number;

  // 父目录id
  @Prop()
  parentId: string;

  // 方案id
  @Prop()
  drugSchemeId: string;

  // 药品分类id
  @Prop()
  drugSortId: string;

  // 药品分类id
  @Prop({ required: true })
  drugId: string;

  // 药品分类id
  @Prop({ required: true })
  specificationId: string;

  @Prop({ type: Boolean, default: false })
  value!: boolean;

  @Emit("success")
  addSuccess(e?) {}

  editOptions = {
    stylingMode: "outlined",
    placeholder: "请输入",
  };

  getSimpleSuffix(
    text: string,
    extendOptions: dxSelectBoxOptions
  ): dxSelectBoxOptions {
    let options: dxSelectBoxOptions = {
      stylingMode: "outlined",
      buttons: [
        {
          name: "unit",
          location: "after",
          options: {
            text: text,
            stylingMode: "text",
          },
        },
      ],
    };

    return Object.assign({}, extendOptions, options);
  }
  getSelectBoxOptions(extendOptions: dxSelectBoxOptions) {}

  // 药品选择器设置
  get durgSetting(): dxSelectBoxOptions {
    return this.setTagSetting([]);
  }
  // 规格
  get skuSetting(): dxSelectBoxOptions {
    return this.setTagSetting([], {
      displayExpr: "specificationName",
      valueExpr: "specificationId",
    });
  }

  // 设置选择器
  setTagSetting(items: any[], addedOptions: dxSelectBoxOptions = {}) {
    let defaultSetting = {
      stylingMode: "outlined",
      displayExpr: "drugName",
      valueExpr: "drugId",
      searchEnabled: true,
      searchExpr: "drugName",
      showDropDownButton: true,
    } as dxSelectBoxOptions;
    return Object.assign(defaultSetting, { items }, addedOptions);
  }

  popupVisible = this.value || false;

  dataSource = [];

  @Inject()
  apiTool: ApiTool;

  created() {
    let client = this.apiTool.createClient(DrugClient);
    let specificationClient = this.apiTool.createClient(SpecificationClient);
    let selfMadeDrugClient = this.apiTool.createClient(SelfMadeDrugClient);
    this.drugData = new DrugData(client, this);
    this.drugSkuData = new DrugSkuData(specificationClient, this);
    this.drugMadeData = new DrugMadeData(selfMadeDrugClient, this);
  }

  // 初始化弹窗
  initPopup() {
    this.getDrugDetail();
    this.setDrugDatalist();
  }

  // 药品详情
  drugData: DrugData;
  drugDetail: OutPutDrugInfo = {};
  async getDrugDetail() {
    this.drugDetail = await this.drugData.info(this.drugId, this.drugSchemeId);
  }

  // 规格
  drugSkuData: DrugSkuData;
  agreeDrugBase: AgreeDrug = {
    selected: false,
    drugId: "",
    specificationId: "",
    adoption: 0,
    specificationList: [] as any[],
  };
  agreeDrugList: AgreeDrug[] = [];
  // 添加
  add() {
    this.agreeDrugList = this.agreeDrugList.concat(
      Object.assign({}, this.agreeDrugBase)
    );
  }
  // 删除
  deleteItem() {
    let drugCompatilitys: any[] = [];
    for (let key in this.agreeDrugList) {
      let item = this.agreeDrugList[key];
      let isDelete = item.selected;
      if (!isDelete) {
        drugCompatilitys.push(item);
      }
    }
    this.agreeDrugList = drugCompatilitys;
  }

  // // 药品列表
  // drugList: OutPutDrugInfo[] | any = [];
  // async getDrugList(value) {
  //   let res = await this.drugData.searchByNameWBPY(value);
  //   this.drugList = res.data;
  // }

  // 药品列表源
  drugDatalist: DataSource = null;
  setDrugDatalist() {
    this.drugDatalist = new DataSource({
      key: "drugId",
      load: (options) => {
        console.log("load", options);
        let searchValue = options.searchValue || "";
        return this.drugData.searchByNameWBPY(searchValue);
      },
      byKey: async (key) => {
        if (!key) {
          return;
        }
        let data = await this.drugData.info(key, this.drugSchemeId);
        let info = {
          drugName: data.name,
          drugId: data.drugId,
        };
        return info;
      },
    });
  }

  // 规格列表
  // drugSkuList: OutputSpecificationSimpleModel[] | any = [];
  async getDrugSkuList(drugId) {
    let res = await this.drugSkuData.getList({
      drugId,
      pageInfo: {
        index: 0,
        pageSize: 10,
      },
    });
    return res.data as OutputSpecificationSimpleModel[];
  }
  // 药品选中改变
  async drugChange(index) {
    let agreeDrugList = this.agreeDrugList;
    let item = agreeDrugList[index];
    let drugId = item.drugId || "";
    let skuList = await this.getDrugSkuList(drugId);
    agreeDrugList[index] = {
      ...item,
      specificationList: skuList,
    };
    console.log("this.agreeDrugList", this.agreeDrugList);
    this.agreeDrugList = agreeDrugList;
  }
  // 根据id获取规格名称
  getSkuName(id: string, list: OutputSpecificationSimpleModel[]) {
    let skuItem = list.find((item) => {
      if (item.specificationId == id) {
        return item;
      }
    });
    return skuItem ? skuItem.specificationName : "";
  }

  @Watch("value")
  watchValue() {
    this.popupVisible = this.value;
  }

  hidden() {
    this.popupVisible = false;
    this.$emit("update:value", this.popupVisible);
  }
  // 提交
  drugMadeData: DrugMadeData;
  submit() {
    let insertOrUpdateAgreementDrugInputs: InsertOrUpdateSelfMadeDrugInput[] =
      this.agreeDrugList.map((item) => {
        let { adoption, specificationId } = item;
        return {
          adoption,
          specificationId,
        };
      });
    let params: BatchInsertOrUpdateSelfMadeDrugInput = {
      specificationId: this.specificationId,
      insertOrUpdateAgreementDrugInputs,
    };
    this.drugMadeData.add(params).then((isSuccess) => {
      if (isSuccess) {
        this.hidden();
        this.addSuccess();
      }
    });
  }
}
</script>

<style lang="scss" scoped>
.title {
  height: 56px;
  padding: 15px;
  .title-content {
    display: flex;
    justify-content: space-between;

    .title-operation {
      display: flex;
      justify-content: space-between;
    }
  }
}
.pishi {
  display: flex;
  // justify-content: start;
  align-items: center;
}
.center-title {
  color: black;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.lb-form-button-right {
  .div1 {
    padding: 10px;
    width: 100%;
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
}
.item-template {
  p {
    width: 50px;
  }
  div.dx-selectbox,
  div.dx-textbox {
    flex: 3;
  }
}
.notice {
  justify-content: flex-end;
  > span {
    margin-left: 12px;
    width: 180px;
  }
}
</style>
